#include <stdio.h>
#include <string>
#include <vector>
#include <unistd.h>
#include <functional>
#include <algorithm>

#include "thread/Latch.h"
#include "thread/current_thread.h"
#include "thread/Thread.h"


void testFunc()
{
  printf("test func\n");
}
class Test
{
 public:
  Test(int numThreads)
    : latch_(1),
      threads_{}
  {
    for (int i = 0; i < numThreads; ++i)
    {
      char name[32] = {0};
      snprintf(name, sizeof(name), "work thread %d", i);
      auto t = std::make_shared<Thread>(std::bind(&Test::threadFunc, this), std::string(name));
      threads_.push_back(t);


    } 

    for (const auto &t : threads_)
      t->start();  
  }

  void run()
  {
    latch_.count_down();
  }

  void joinAll()
  {
    for (const auto &t : threads_)
      t->join();
  }

  void threadFunc()
  {
    latch_.wait();
    printf("tid=%d, %s started\n",
           CurrentThread::tid(),
           CurrentThread::thread_name());

    

    printf("tid=%d, %s stopped\n",
           CurrentThread::tid(),
           CurrentThread::thread_name());
  }

  Latch latch_;
  std::vector<std::shared_ptr<Thread>> threads_;
};

int main()
{
  printf("pid=%d, tid=%d\n", ::getpid(), CurrentThread::tid());
  CurrentThread::set_thread_name("main thread");
  Test t(3);
  sleep(1);
  printf("pid=%d, tid=%d %s running ...\n", ::getpid(), CurrentThread::tid(), CurrentThread::thread_name());
  t.run();
  t.joinAll();

  printf("number of created threads %d\n", Thread::TOTAL().load());
}


